package tijava.concurrency;

import java.util.concurrent.*;
import java.util.*;

class Accessor implements Runnable {
	private final int id;
	private ThreadLocalHolder holder;

	public Accessor(int idn, ThreadLocalHolder holder) {
		id = idn;
		this.holder = holder;
	}

	public void run() {
		while (true) {
			holder.increment();
			System.out.println(this);
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public String toString() {
		return "#" + id + ": " + holder.get();
	}
}

class ThreadLocalHolder {
	private ThreadLocal<Integer> value = new ThreadLocal<Integer>() {
		private Random rand = new Random(47);

		protected synchronized Integer initialValue() {
			System.out.println("call initialValue when the thread call get at the first time");
			return rand.nextInt(10000);
		}
	};

	public void increment() {
		value.set(value.get() + 1);
	}

	public int get() {
		return value.get();
	}

}

public class ThreadLocalDemo {
	public static void main(String[] args) throws Exception {
		ThreadLocalHolder holder = new ThreadLocalHolder();
		Thread t1 = new Thread(new Accessor(1, holder));
		Thread t2 = new Thread(new Accessor(2, holder));
		t1.setDaemon(true);
		t2.setDaemon(true);

		t1.start();
		t2.start();
		TimeUnit.SECONDS.sleep(5);
	}
}